/**
 * 微信消息类开放接口
 */
import request from 'request';
import { getWxAccountToken, getWxappToken } from './token';
import { WX_MINIPROGRAM_APP_ID } from '../../config';
import { addWxImage } from './image';

const WX_TEMPLATE_INTERFACE = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send';
const WX_CARD_INTERFACE = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
const DEFAULT_BOOK_IMAGE = 'https://picture-1256514897.file.myqcloud.com/mbook/0a35db60-6702-11ec-ba5b-294a923da5de.jpg';

/**
 * 发送微信模板消息
 * @param {*} openid 用户唯一 ID
 * @param {*} templateId 消息模板 ID
 * @param {*} page 打开页面
 * @param {*} data 消息内容
 * @returns
 */
export async function sendWxTemplateMsg(openid, templateId, page, data) {
  const token = await getWxappToken();
  console.log('请求token', token);
  console.log('用户opendid', openid);
  console.log('模板id', templateId);
  console.log('消息跳转页面', page);
  console.log('消息', data);
  return new Promise((resolve, reject) => {
    /**
     * 请求方式以及参数说明见
     * 文档 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
     */
    request(
      {
        method: 'POST',
        url: `${WX_TEMPLATE_INTERFACE}?access_token=${token}`,
        json: true,
        body: {
          touser: openid,
          template_id: templateId,
          page,
          data
        },
        headers: {
          'Content-type': 'application/json'
        }
      },
      (error, response, body) => {
        if (error) {
          console.log('接口地址', `${WX_TEMPLATE_INTERFACE}?access_token=${token}`);
          console.log('微信接口请求失败', error);
          reject(error);
          return;
        }
        console.log('发送微信模板消息成功', body);
        resolve(body);
      }
    );
  });
}

/**
 * 发送微信客服消息
 * @param {*} touser 发送用户
 * @param {*} title 标题
 * @param {*} page 打开页面
 * @param {*} data 消息内容
 * @returns
 */
export async function sendWxCardMsg({ touser = '', title = '', page = '/pages/index/index', imageUrl = DEFAULT_BOOK_IMAGE }) {
  const token = await getWxAccountToken(true);
  const mediaId = await addWxImage(imageUrl);
  console.log('请求token', token);
  console.log('用户opendid', touser);
  console.log('标题', title);
  console.log('页面路径', page);
  console.log('素材 ID', mediaId);
  return new Promise((resolve, reject) => {
    /**
     * 请求方式以及参数说明见
     * 文档 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/customer-message/customerServiceMessage.send.html#method-http
     */
    request(
      {
        method: 'POST',
        url: `${WX_CARD_INTERFACE}?access_token=${token}`,
        json: true,
        body: {
          touser,
          msgtype: 'miniprogrampage',
          miniprogrampage: {
            title,
            appid: WX_MINIPROGRAM_APP_ID,
            pagepath: page,
            thumb_media_id: mediaId
          }
        },
        headers: { 'Content-type': 'application/json' }
      },
      (error, response, body) => {
        if (error) {
          console.log('接口地址', `${WX_CARD_INTERFACE}?access_token=${token}`);
          console.log('微信接口请求失败', error);
          reject(error);
          return;
        }
        if (body.errcode == 0) {
          console.log('回复小程序卡片成功');
          resolve(true);
        } else {
          console.log('返回值', body);
          reject(new Error(body.errmsg));
        }
      }
    );
  });
}
